﻿namespace WPFDBBrowser.Settings
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Xml.Serialization;

    public abstract class SettingsBase<TSettings>
    {
        private string _fileName;

        public SettingsBase(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
                throw new ArgumentNullException("fileName");
            this._fileName = fileName;
        }

        public bool Exist
        {
            get
            {
                return File.Exists(this._fileName);
            }
        }

        public abstract bool SaveSettings();
        public abstract bool LoadSettings();

        protected virtual void Save(TSettings settings)
        {
            TextWriter writer = null;
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(TSettings));
                writer = new StreamWriter(this._fileName, false);
                serializer.Serialize(writer, settings);
            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }
        }

        protected virtual object Load()
        {
            if (!File.Exists(this._fileName))
                return null;
            TextReader reader = null;
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(TSettings));
                reader = new StreamReader(this._fileName);
                return serializer.Deserialize(reader);
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }
        }
    }
}
